/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_cyclonedds/converter/InstanceHandleConverter.hpp"

const uint32_t bit_24 = 24;
const uint32_t bit_16 = 16;
const uint32_t bit_8 = 8;

InstanceHandleConverter* InstanceHandleConverter::singleton_ = nullptr;

InstanceHandleConverter::InstanceHandleConverter() {}

InstanceHandleConverter* InstanceHandleConverter::GetInstance()
{
    if (singleton_ == nullptr) {
        singleton_ = new InstanceHandleConverter();
    }
    return singleton_;
}

dal_ret_t
InstanceHandleConverter::ConvertInstanceHandleFromDalToCyclonedds(dal_instance_handle_t* d_ins,
                                                               dds_instance_handle_t* c_ins)
{
    if (c_ins == nullptr || d_ins == nullptr)
        return DAL_RETCODE_BAD_PARAMETER;
    *c_ins = d_ins->segment_1_;
    (*c_ins) = (*c_ins) << 32;
    (*c_ins) |= d_ins->segment_0_;
    return DAL_RETCODE_OK;
}

dal_ret_t
InstanceHandleConverter::ConvertInstanceHandleFromCycloneddsToDal(const dds_instance_handle_t* c_ins,
                                                               dal_instance_handle_t* d_ins)
{
    if (c_ins == nullptr || d_ins == nullptr)
        return DAL_RETCODE_BAD_PARAMETER;
    d_ins->segment_0_ = uint32_t(*c_ins);
    d_ins->segment_1_ = uint32_t((*c_ins) >> 32);
    d_ins->segment_2_ = 0u;
    d_ins->segment_3_ = 0u;

    return DAL_RETCODE_OK;
}